//
//  KY19AdvertView.m
//  KYMobClick
//
//  Created by 01 on 16/11/8.
//  Copyright © 2016年 Czj. All rights reserved.
//

#import "KY19AdvertView.h"

@interface KY19AdvertView()
@property (nonatomic, strong) UIImageView                   *imgView;
@property (nonatomic, strong) UIButton                      *deleteBtn;
@property (nonatomic, strong) NSMutableDictionary           *dict;
@end

@implementation KY19AdvertView

#pragma mark - Init
- (instancetype)init {
    self = [super init];
    if (self) {
        self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,kDeviceWidth, kCurrentScreenWidth(80))];
        [self addSubview:self.imgView];
        [self createTap];
    }
    return self;
}

#pragma mark - Public methods
- (void)createContent:(NSDictionary *)dataDic blockHeight:(void (^)(NSInteger))viewHeight {
    self.dict = [NSMutableDictionary dictionaryWithDictionary:dataDic];
    NSString *pathDocument = [KYSystemInfo getSaveAdvertImagePath];
    NSString *imageUrl;
    NSString *imagePath;
    if (dataDic && dataDic[@"data"]) {
        imageUrl = dataDic[@"data"][@"imageurl"];
        imagePath = [pathDocument stringByAppendingString:[NSString stringWithFormat:@"%@.png",self.dict[@"data"][@"adsid"]]];
    }
    UIImage *cacheImage = [UIImage imageWithContentsOfFile:imagePath];
    [self.imgView KYSD_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:cacheImage options:KYSDWebImageAllowInvalidSSLCertificates completed:^(UIImage *image, NSError *error, KYSDImageCacheType cacheType, NSURL *imageURL) {
        if (image) {
            [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
            CGSize size = image.size;
            CGFloat height= size.height;
            CGFloat width = size.width;
            if (viewHeight) viewHeight(kDeviceWidth / width * height + KY_MARGIN);
            self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, KY_MARGIN/2,kDeviceWidth,kDeviceWidth / width * height)];
            [self postPVData];
        }else{
        }
    }];
}

// 添加手势
- (void)createTap {
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeOtherPage:)];
    self.imgView.userInteractionEnabled = YES;
    [self.imgView addGestureRecognizer:tap];
}

#pragma mark - Response methods
/**
 统计PV数据
 */
- (void)postPVData {
    //发送统计数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"advertPVData" object:self.dict[@"data"]];
}
//广告试图事件跳转 同时触发post页面统计请求
- (void)changeOtherPage:(NSDictionary *)dict {
//    [self.dict setValue:kOnClick forKey:@"clickStatus"];
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickView:)]) {
        [self.delegate clickView:self.dict[@"data"]];
    }
}

#pragma mark - Lazy load
- (NSMutableDictionary *)dict {
    if (!_dict) {
        _dict = [[NSMutableDictionary alloc] init];
    }
    return _dict;
}
@end
